{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="bi bi-speedometer2 me-2"></i>管理员仪表板
    </h2>
    <div class="btn-group">
        <button class="btn btn-outline-primary" onclick="refreshStats()">
            <i class="bi bi-arrow-clockwise me-1"></i>刷新数据
        </button>
        <button class="btn btn-outline-warning" onclick="cleanupSystem()">
            <i class="bi bi-trash me-1"></i>系统清理
        </button>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card text-white bg-primary">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title">{{ stats.users.total }}</h4>
                        <p class="card-text">总用户数</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-people display-4"></i>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <small>活跃用户: {{ stats.users.active }}</small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card text-white bg-success">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title">{{ stats.emails.total }}</h4>
                        <p class="card-text">总邮件数</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-envelope display-4"></i>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <small>今日: {{ stats.emails.today }}</small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card text-white bg-info">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title">{{ stats.emails.unread }}</h4>
                        <p class="card-text">未读邮件</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-envelope-fill display-4"></i>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <small>占比: {{ "%.1f"|format((stats.emails.unread / stats.emails.total * 100) if stats.emails.total > 0 else 0) }}%</small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card text-white bg-warning">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title">{{ stats.emails.week }}</h4>
                        <p class="card-text">本周邮件</p>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-calendar-week display-4"></i>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <small>最近7天</small>
            </div>
        </div>
    </div>
</div>

<!-- 图表区域 -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-graph-up me-2"></i>邮件发送趋势
                </h5>
            </div>
            <div class="card-body">
                <canvas id="emailTrendChart" height="100"></canvas>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-pie-chart me-2"></i>用户角色分布
                </h5>
            </div>
            <div class="card-body">
                <canvas id="userRoleChart" height="200"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 最近活动 -->
<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-clock-history me-2"></i>最近注册用户
                </h5>
                <a href="{{ url_for('admin.users') }}" class="btn btn-sm btn-outline-primary">
                    查看全部
                </a>
            </div>
            <div class="card-body">
                {% if recent_users %}
                    <div class="list-group list-group-flush">
                        {% for user in recent_users %}
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <strong>{{ user.username }}</strong>
                                    <br>
                                    <small class="text-muted">{{ user.email }}</small>
                                </div>
                                <div class="text-end">
                                    <span class="badge bg-{{ 'success' if user.is_active else 'secondary' }}">
                                        {{ '活跃' if user.is_active else '未激活' }}
                                    </span>
                                    <br>
                                    <small class="text-muted">
                                        {{ user.created_at.strftime('%m-%d %H:%M') }}
                                    </small>
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                {% else %}
                    <p class="text-muted text-center">暂无最近注册用户</p>
                {% endif %}
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-envelope-paper me-2"></i>最近邮件
                </h5>
                <a href="{{ url_for('admin.emails') }}" class="btn btn-sm btn-outline-primary">
                    查看全部
                </a>
            </div>
            <div class="card-body">
                {% if recent_emails %}
                    <div class="list-group list-group-flush">
                        {% for email in recent_emails %}
                            <div class="list-group-item">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">{{ email.subject[:30] }}{% if email.subject|length > 30 %}...{% endif %}</h6>
                                        <p class="mb-1 text-muted">
                                            {{ email.sender.username }} → {{ email.recipient.username }}
                                        </p>
                                        <small class="text-muted">
                                            {{ email.sent_at.strftime('%m-%d %H:%M') }}
                                        </small>
                                    </div>
                                    <div>
                                        {% if email.is_read %}
                                            <i class="bi bi-envelope-open text-muted"></i>
                                        {% else %}
                                            <i class="bi bi-envelope-fill text-primary"></i>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                {% else %}
                    <p class="text-muted text-center">暂无最近邮件</p>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 系统信息 -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-info-circle me-2"></i>系统信息
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <strong>系统版本：</strong><br>
                        <span class="text-muted">邮箱演示系统 v1.0</span>
                    </div>
                    <div class="col-md-3">
                        <strong>数据库：</strong><br>
                        <span class="text-muted">SQLite</span>
                    </div>
                    <div class="col-md-3">
                        <strong>运行时间：</strong><br>
                        <span class="text-muted" id="uptime">计算中...</span>
                    </div>
                    <div class="col-md-3">
                        <strong>最后更新：</strong><br>
                        <span class="text-muted">{{ datetime.now().strftime('%Y-%m-%d %H:%M:%S') }}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let emailTrendChart;
let userRoleChart;

document.addEventListener('DOMContentLoaded', function() {
    initCharts();
    updateUptime();
    setInterval(updateUptime, 60000); // 每分钟更新一次运行时间
});

// 初始化图表
async function initCharts() {
    try {
        const response = await apiRequest('/admin/api/statistics');
        if (response.success) {
            createEmailTrendChart(response.data.daily_emails);
            createUserRoleChart(response.data.user_roles);
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 创建邮件趋势图表
function createEmailTrendChart(data) {
    const ctx = document.getElementById('emailTrendChart').getContext('2d');
    
    emailTrendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: data.map(item => item.date),
            datasets: [{
                label: '邮件数量',
                data: data.map(item => item.count),
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

// 创建用户角色分布图表
function createUserRoleChart(data) {
    const ctx = document.getElementById('userRoleChart').getContext('2d');
    
    userRoleChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['普通用户', '管理员'],
            datasets: [{
                data: [data.student || 0, data.admin || 0],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.8)',
                    'rgba(255, 99, 132, 0.8)'
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 99, 132, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

// 刷新统计数据
async function refreshStats() {
    try {
        showAlert('正在刷新数据...', 'info');
        
        // 重新加载页面数据
        window.location.reload();
    } catch (error) {
        showAlert('刷新失败: ' + error.message, 'danger');
    }
}

// 系统清理
async function cleanupSystem() {
    if (!confirm('确定要执行系统清理吗？这将永久删除已标记删除的邮件数据。')) {
        return;
    }
    
    try {
        const response = await apiRequest('/admin/api/cleanup', {
            method: 'POST'
        });
        
        if (response.success) {
            showAlert(`系统清理完成，清理了 ${response.cleaned_count} 条记录`, 'success');
            setTimeout(() => window.location.reload(), 2000);
        }
    } catch (error) {
        showAlert('系统清理失败: ' + error.message, 'danger');
    }
}

// 更新运行时间
function updateUptime() {
    const startTime = new Date('{{ datetime.now().strftime("%Y-%m-%d %H:%M:%S") }}');
    const now = new Date();
    const uptime = Math.floor((now - startTime) / 1000);
    
    const hours = Math.floor(uptime / 3600);
    const minutes = Math.floor((uptime % 3600) / 60);
    const seconds = uptime % 60;
    
    document.getElementById('uptime').textContent = 
        `${hours}小时 ${minutes}分钟 ${seconds}秒`;
}

// 实时数据更新（每30秒）
setInterval(async function() {
    try {
        const response = await apiRequest('/admin/api/statistics');
        if (response.success) {
            // 更新统计卡片
            updateStatsCards(response.data);
        }
    } catch (error) {
        console.error('更新实时数据失败:', error);
    }
}, 30000);

// 更新统计卡片
function updateStatsCards(data) {
    // 这里可以添加实时更新统计卡片的逻辑
    // 由于模板渲染的限制，暂时通过页面刷新来更新
}
</script>
{% endblock %}